import Vue,{PropOptions,VNode} from 'vue';
import {convertCssLength} from '../../../util/common';
import {PlainObject,StandardOption} from '../../../../types';
/**
 * 选项类型
 */
export type OptionType=PlainObject|string;
/**
 * 列类型
 */
export type ColumnType=Array<OptionType>;
/**
 * 多列类型
 */
export type ColumnsType=Array<ColumnType>;
/**
 *
 * @author 唐国雄
 * @date 2021/8/3
 * 属性----------------------
 */
export default Vue.extend({
	name:'Picker',
	props:{
		//当前值
		value:{
			type:Array,
			required:true,
		} as PropOptions<Array<any>>,
		//选项列
		columns:{
			type:Array,
			required:true,
		} as PropOptions<ColumnsType>,
		//级联字段
		childrenKey:String,
		//值属性
		optionValue:{
			type:String,
			default:'value'
		},
		//显示属性
		optionLabel:{
			type:String,
			default:'label'
		},
		//选项高度
		itemHeight:{
			type:[Number,String],
			default:44
		},
		//标题
		title:String,
		//确定按钮文字
		confirmText:{
			type:String,
			default:'确定'
		},
		//取消按钮文字
		closeText:{
			type:String,
			default:'取消'
		},
		//禁用
		disable:Boolean,
		//加载状态
		loading:Boolean,
	},
	computed:{
		classes():string{
			return 'lexmis-Picker';
		},
		//选项高度
		itemHeightStr():string{
			return convertCssLength(this.itemHeight);
		},
		//标准化后的选项列
		normalizedColumns():Array<Array<StandardOption>>{
			const {optionValue,optionLabel,childrenKey,value}=this;
			if(childrenKey){
				const result:Array<Array<StandardOption> >=[];
				const buildColumns=function(column:ColumnType,deep:number){
					let match=0;
					result.push(column.map(function(option,index){
						if(typeof option==='string'){
							return {label:option,value:option};
						}
						const curValue=option[optionValue];
						if(curValue===value[deep]){
							match=index;
						}
						return {
							label:option[optionLabel],
							value:curValue,
						};
					}));
					const matchColumn=column[match];
					if(matchColumn&&typeof matchColumn!=='string'&&Array.isArray(matchColumn[childrenKey])){
						buildColumns(matchColumn[childrenKey],deep+1);
					}
				};
				buildColumns(this.columns[0]??[],0);
				return result;
			}else{
				return this.columns.map((column) => {
					return column.map((option) => {
						if(typeof option==='string'){
							return {label:option,value:option};
						}
						return {
							label:option[optionLabel],
							value:option[optionValue],
						};
					});
				});
			}
		},
	},
	render(h):VNode{
		return h('div',{
			staticClass:this.classes,
		},[
			this.title
				?h('div',{
					staticClass:'lexmis_title',
				})
				:null,
			h('div',{
				staticClass:'lexmis_body',
			},this.normalizedColumns.map((column) => {
				return h('div',{
					staticClass:'lexmis_column_placeholder',
				},[
					h('div',{
						staticClass:'lexmis_column',
					},column.map((option) => {
						return h('div',{
							staticClass:'lexmis_option',
							staticStyle:{
								height:this.itemHeightStr,
							}
						},option.label);
					}))
				]);
			}))
		]);
	}
});
